package com.xzzz.irda.guardcat.core.metric.bufferpool;


import cn.hutool.core.collection.CollectionUtil;

import java.io.Serializable;
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
import java.nio.ByteBuffer;
import java.util.List;

/**
 * 缓冲池信息【nio 中的直接内存信息】
 * -XX:+UseParallelGC -XX:+UseParallelOldGC -Xss512K -Xms1408M -Xmx1408M -XX:NewRatio=2 -XX:SurvivorRatio=8 -XX:MetaspaceSize=384M -XX:MaxMetaspaceSize=384M -XX:MaxDirectMemorySize=256M
 *
 * @author xzzz
 * @since 1.0.0
 */
public class BufferPoolInfo implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * java.nio.DirectByteBuffer 的使用信息
     */
    private BufferInfo directBufferInfo;

    /**
     * java.nio.MappedByteBuffer 的使用信息
     */
    private BufferInfo mappedBufferInfo;

    /**
     * 构造器私有化
     */
    private BufferPoolInfo() {
    }

    /**
     * 获取缓冲池信息【nio 中的直接内存信息】
     *
     * @return BufferPoolInfo 缓冲池信息
     */
    public static BufferPoolInfo getBufferPoolInfo() {
        BufferPoolInfo bufferPoolInfo = new BufferPoolInfo();
        List<BufferPoolMXBean> bufferPoolMxBeanList = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
        if (CollectionUtil.isNotEmpty(bufferPoolMxBeanList)) {
            String name;
            BufferInfo bufferInfo;
            for (BufferPoolMXBean bufferPoolMxBean : bufferPoolMxBeanList) {
                name = bufferPoolMxBean.getName();
                bufferInfo = new BufferInfo(name, bufferPoolMxBean.getCount(), bufferPoolMxBean.getTotalCapacity(), bufferPoolMxBean.getMemoryUsed());
                if ("direct".equals(name)) {
                    bufferPoolInfo.directBufferInfo = bufferInfo;
                } else if ("mapped".equals(name)) {
                    bufferPoolInfo.mappedBufferInfo = bufferInfo;
                }
            }
        }
        return bufferPoolInfo;
    }

    public BufferInfo getDirectBufferInfo() {
        return directBufferInfo;
    }

    public BufferInfo getMappedBufferInfo() {
        return mappedBufferInfo;
    }

    @Override
    public String toString() {
        return "缓冲池信息{" +
                "直接缓冲信息=" + directBufferInfo +
                ", 映射缓冲信息=" + mappedBufferInfo +
                '}';
    }

    public static void main(String[] args) throws InterruptedException {
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        ByteBuffer buffer2 = ByteBuffer.allocateDirect(1024);
        System.out.println(buffer.capacity());
        buffer.putInt(123123123);
        buffer.putInt(321);
        buffer.putInt(456);
        buffer.putInt(78909);
        buffer.putInt(3454);
        buffer.putInt(2314467);
        System.out.println(getBufferPoolInfo());
        buffer.putInt(9076543);
        buffer2.putInt(9076543);

    }


}
